package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caifu.bean.HealthyArchiveSearchBean;
import com.caifu.mapper.*;
import com.caifu.pojo.*;
import com.caifu.service.IHealthArchiveService;
import com.caifu.util.AesMyUtil;
import com.caifu.util.Constance;
import com.caifu.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 功能描述：健康档案接口
 *
 * @Author GZ
 * @Date 2020/11/11 14:06
 */
@Service
@PropertySource(value = {"classpath:definition.properties"},encoding = "utf-8")
public class HealthArchiveServiceImpl implements IHealthArchiveService {
    //血糖正常值(最大值)
    @Value("${blood.glucose.high}")
    private double bloodGlucoseHigh;
    //血糖正常值(最小值)
    @Value("${blood.glucose.low}")
    private  double bloodGlucoseLow;
    //高血压（值）
    @Value("${blood.systolic.pressure.high}")
    private  int systolicHigh;
    //低血压（值）
    @Value("${blood.diastolic.pressure.low}")
    private int diastolicLow;

    @Resource
    private YlCostMapper costMapper;
    @Resource
    private YlElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private YlHealthyArchivesMapper archivesMapper;
    @Resource
    private YlBedRecordMapper bedRecordMapper;
    @Resource
    private YsLabelMapper labelMapper;
    @Resource
    private YlNursingRecordMapper nursingRecordMapper;
    @Resource
    private YlAssessmentRecordMapper assessmentRecordMapper;
    @Resource
    private YlContractInfoMapper contractInfoMapper;
    @Resource
    private YlUserHistoryMapper userHistoryMapper;
    @Resource
    private YlPhysiqueCheckMapper checkMapper;
    @Resource
    private YlBloodGlucoseMapper glucoseMapper;
    @Resource
    private YlBloodPressureMapper pressureMapper;
    @Resource
    private YlHealthNursingMapper nursingMapper;

    @Override
    public JSONObject pagedQueryOldManInfoData(int pageNum, int pageSize
            , SysUser sysUser, HealthyArchiveSearchBean searchBean) throws Exception {
        JSONObject resultData = new JSONObject();
        JSONArray dataArray = new JSONArray();
        int totalRecord = 0;
        int dataSize = 0;
        if (pageNum < 1) {
            resultData.put("code", "1001");
            resultData.put("codeDesc", "页数不正确");
            resultData.put("totalRecord", totalRecord);
            return resultData;
        }
        if (null == sysUser) {
            resultData.put("code", "1001");
            resultData.put("codeDesc", "管理员登录超时");
            resultData.put("totalRecord", totalRecord);
            return resultData;
        }

        try {
            if (null == searchBean) {
                searchBean = new HealthyArchiveSearchBean();
            }
            int startCount = (pageNum - 1) * pageSize;
            int endCount = pageNum * pageSize;
            searchBean.setStartCount(startCount);
            searchBean.setEndCount(endCount);
            searchBean.setPensionNo(sysUser.getCurrentPensionNo());
            List<Map<String, Object>> userList = elderlyInfoMapper
                    .pagedQueryElderInfoData(searchBean);
            if (null != userList && userList.size() > 0) {
                dataSize = userList.size();
                for (Map<String, Object> user : userList
                ) {
                    if (null != user) {
                        JSONObject data = new JSONObject();
                        if (Util.isNotNull(user.get("mobile"))) {
                            data.put("mobile", Constance.Null2EmptyTrim(AesMyUtil.Decrypt(user.get("mobile").toString())));
                        }
                        data.put("contactName", Constance.Null2EmptyTrim(user.get("contact_name")));
                        data.put("headUl", Constance.Null2EmptyTrim(user.get("IMG_PATH")));
                        String userNo = Constance.Null2EmptyTrim(user.get("USER_NO"));
                        data.put("userNo", userNo);
                        data.put("userName", Constance.Null2EmptyTrim(user.get("USER_NAME")));
                        String userSex = Constance.Null2EmptyTrim(user.get("USER_SEX"));
                        if ("1".equals(userSex)) {
                            data.put("userSex", "男");
                        } else {
                            data.put("userSex", "女");
                        }
                        data.put("buildingName", Constance.Null2EmptyTrim(user.get("BUILDING_NAME")));
                        data.put("roomName", Constance.Null2EmptyTrim(user.get("ROOM_NAME")));
                        data.put("bedName", Constance.Null2EmptyTrim(user.get("BED_NAME")));

                        String archiveFlag = Constance.Null2EmptyTrim(user.get("is_archive"));
                        if ("0".equals(archiveFlag)) {
                            data.put("symptom", "暂无");
                            data.put("checkDate", "暂无");
                            //计算健康档案时间
                            String userCreateDate = Constance.disposeDateTime(Constance.Null2EmptyTrim(user.get("CREATE_DATE")));
                            Long overHour = Constance.obtainHourInfoByDataTime(userCreateDate);
                            data.put("overHour",48-overHour);
                        } else {
                            YlHealthyArchives archives = queryHealthyArchivesByUserNo(userNo);
                            if (null != archives) {
                                data.put("symptom", archives.getMedicalHistory());
                                data.put("checkDate", Constance.simpleDateFormatOne(archives.getCreateTime().substring(0, 8)));
                                data.put("overHour",0);
                            }
                        }
                        data.put("isArchive", archiveFlag);
                        dataArray.add(data);
                    }
                }
            }
            totalRecord = elderlyInfoMapper.queryElderInfoTotalRecords(searchBean);
            resultData.put("code", "0000");
            resultData.put("codeDesc", "查询成功！");
            resultData.put("data", dataArray);
            resultData.put("dataSize", dataSize);
            resultData.put("totalRecord", totalRecord);
            return resultData;
        } catch (Exception e) {
            e.printStackTrace();
            resultData.put("code", "9999");
            resultData.put("codeDesc", "查询失败");
            resultData.put("totalRecord", 0);
            return resultData;
        }
    }

    @Override
    public JSONObject queryAllHealthyNursingByPensionNo(String pensionNo) throws Exception {
        JSONObject resultData = new JSONObject();
        int totalRecord = 0;
        if(StringUtils.isBlank(pensionNo)){
            resultData.put("code", "1001");
            resultData.put("codeDesc", "养老机构编号为空");
            resultData.put("totalRecord", 0);
            return resultData;
        }
        //查询护理等级变更信息
        List<Map<String,Object>> nursingList = nursingMapper
                .queryAllHealthyNursingByPensionNo(pensionNo);
        if(null!=nursingList&&nursingList.size()>0){
            totalRecord = nursingList.size();
        }
        //查询未读消息数量
        int unReadCount = nursingMapper.queryUnReadHealthyNursing(pensionNo);
        resultData.put("code", "0000");
        resultData.put("nursingList", nursingList);
        resultData.put("code", "0000");
        resultData.put("totalRecord", totalRecord);
        resultData.put("unReadCount", unReadCount);
        return resultData;
    }

    @Override
    public JSONObject queryElderlyUserInfo(String userNo) throws Exception {
        JSONObject result = new JSONObject();
        try {
            QueryWrapper<YlElderlyInfo> elderlyInfoQueryWrapper = new QueryWrapper<>();
            elderlyInfoQueryWrapper.eq("USER_NO",userNo);
            YlElderlyInfo elderlyInfo = elderlyInfoMapper.selectOne(elderlyInfoQueryWrapper);
            if(null!=elderlyInfo){
                //头像
                if(StringUtils.isNotBlank(elderlyInfo.getImgPath())){
                    result.put("headUrl",Constance.Null2EmptyTrim(elderlyInfo.getImgPath()));
                    result.put("headExist","1");
                }else {
                    result.put("headUrl","");
                    result.put("headExist","0");
                }
                //姓名
                result.put("userName",Constance.Null2EmptyTrim(elderlyInfo.getUserName()));
                //性别
                result.put("sex",elderlyInfo.getUserSex());
                result.put("userSex","1".equals(elderlyInfo.getUserSex())?"男":"女");
                //年龄
                result.put("userAge",Constance.Null2EmptyTrim(elderlyInfo.getAge()));
                //学历
                result.put("eductionCode",Constance.Null2EmptyTrim(elderlyInfo.getEducation()));
                result.put("eduction",labelMapper.getLabelNameByLabelCode(elderlyInfo.getEducation()));
                //认知
                result.put("cognitionStatus",Constance.Null2EmptyTrim(elderlyInfo.getCognitionStatus()));
                //社保类型 SOCIAL_SECURITY_TYPE
                result.put("securityType",labelMapper.getLabelNameByLabelCode(elderlyInfo.getSocialSecurityType()));
                //家庭住址
                result.put("userAddress",Constance.Null2EmptyTrim(elderlyInfo.getLiveAddress()));
                //民族
                result.put("nation",Constance.Null2EmptyTrim(elderlyInfo.getNation()));
                //工作单位
                result.put("workPlace",Constance.Null2EmptyTrim(elderlyInfo.getRetireCompany()));
                // 职位
                result.put("occupation",Constance.Null2EmptyTrim(elderlyInfo.getOccupation()));
                //查询合同信息
                YlContractInfo contractInfo = contractInfoMapper
                        .queryMaxContractEndDate(Constance.Null2EmptyTrim(elderlyInfo.getUserNo()));
                if(null!=contractInfo){
                    String statDate =Constance.Null2EmptyTrim(contractInfo.getStartDate());
                    String endDate = Constance.Null2EmptyTrim(contractInfo.getEndDate());
                    result.put("inDate",Constance.simpleDateFormatOne(statDate));
                    result.put("contractEndDate",Constance.simpleDateFormatOne(endDate));
                }
            }
            //查询用户当前有效床位信息
            Map<String,Object> bedMap = bedRecordMapper.queryOldUserBedInfo(userNo);
            if(null!=bedMap){
                StringBuffer sb = new StringBuffer();
                sb.append(bedMap.get("BUILDING_NAME")+"-");
                sb.append(bedMap.get("FLOOR_NAME")+"-");
                sb.append(bedMap.get("ROOM_NAME")+"-");
                sb.append(bedMap.get("BED_NAME"));
                result.put("bedInfo",sb.toString());
            }
            //查询护理等级
            Map<String,Object> nursingInfo = nursingRecordMapper.queryUserNursingDegreeByUserNo(userNo);
            if(null!=nursingInfo){
                result.put("nursingDegree",nursingInfo.get("COST_NAME"));
                result.put("nursingImg",nursingInfo.get("COST_IMG"));
                result.put("nursingDate",Constance.simpleDateFormatOne(Constance
                        .Null2EmptyTrim(nursingInfo.get("next_effect_date"))));
            }
            //查询评估等级
            Map<String,Object> assessmentInfo = assessmentRecordMapper.queryAssessmentInfo(userNo);
            if(null!=assessmentInfo){
                result.put("assessmentDegree",assessmentInfo.get("COST_NAME"));
                result.put("assessmentDate",Constance.simpleDateFormatOne(Constance
                        .Null2EmptyTrim(assessmentInfo.get("VALID_DATE"))));
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public YlHealthyArchives queryHealthyArchivesInfo(String userNo) throws Exception {
        try {
            QueryWrapper<YlHealthyArchives> archivesQueryWrapper = new QueryWrapper<>();
            archivesQueryWrapper.eq("USER_NO",userNo);
            return archivesMapper.selectOne(archivesQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public YlUserHistory queryUserHistoryInfo(String userNo) throws Exception {
        try {
            QueryWrapper<YlUserHistory> userHistoryQueryWrapper = new QueryWrapper<>();
            userHistoryQueryWrapper.eq("USER_NO",userNo);
            YlUserHistory history = userHistoryMapper.selectOne(userHistoryQueryWrapper);
            if(null!=history){
                history.setEductionName(labelMapper.getLabelNameByLabelCode(history.getEducation()));
                history.setMarriageName(labelMapper.getLabelNameByLabelCode(history.getMarriage()));
            }
            return history;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public YlPhysiqueCheck queryUserPhysiqueCheckByUserNo(String userNo) throws Exception {
        try {
            QueryWrapper<YlPhysiqueCheck> physiqueCheckQueryWrapper = new QueryWrapper<>();
            physiqueCheckQueryWrapper.eq("USER_NO",userNo);
            return checkMapper.selectOne(physiqueCheckQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public YlHealthyArchives queryHealthyArchivesByUserNo(String userNo) throws Exception {

        try {
            QueryWrapper<YlHealthyArchives> archivesQueryWrapper = new QueryWrapper<>();
            archivesQueryWrapper.eq("USER_NO", userNo);
            YlHealthyArchives archives = archivesMapper.selectOne(archivesQueryWrapper);
            if(null!=archives){
                archives.setJobName(labelMapper.getLabelNameByLabelCode(archives.getJob()));
                archives.setNationName(labelMapper.getLabelNameByLabelCode(archives.getNation()));
            }
            return archives;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveBasicHealthyInfo(YlHealthyArchives healthyArchives
            , YlUserHistory history, SysUser sysUser) throws Exception {
        JSONObject result = new JSONObject();
        if(null==sysUser){
            result.put("code","1001");
            result.put("codeDesc","管理员登录超时！");
            return result;
        }
        if(null==healthyArchives||null==history){
            result.put("code","1002");
            result.put("codeDesc","要添加的信息为空！");
            return result;
        }
        try {
            //查询健康档案是否窜在
            YlHealthyArchives oldArchives = queryHealthyArchivesByUserNo(healthyArchives.getUserNo());
            healthyArchives.setTellerNo(sysUser.getUserNo()+"");
            healthyArchives.setCreateTime(Constance.currentDateTime());
            history.setTellerNo(sysUser.getUserNo()+"");
            history.setCreateTime(Constance.currentDateTime());
            if(null==oldArchives){
                //如果基本信息不存在则添加
                archivesMapper.insert(healthyArchives);
            }else {
                QueryWrapper<YlHealthyArchives> archivesQueryWrapper = new QueryWrapper<>();
                archivesQueryWrapper.eq("USER_NO",healthyArchives.getUserNo());
                archivesMapper.update(healthyArchives,archivesQueryWrapper);
            }
            YlUserHistory oldHistory = queryUserHistoryInfo(healthyArchives.getUserNo());
            if(null==oldHistory){
                userHistoryMapper.insert(history);
            }else {
                QueryWrapper<YlUserHistory> userHistoryQueryWrapper = new QueryWrapper<>();
                userHistoryQueryWrapper.eq("USER_NO",healthyArchives.getUserNo());
                userHistoryMapper.update(history,userHistoryQueryWrapper);
            }
            result.put("code","0000");
            result.put("codeDesc","保存成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("code","9999");
            result.put("codeDesc","添加失败！");
            return result;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject savePhysiqueCheckInfo(YlPhysiqueCheck physiqueCheck
            , SysUser sysUser) throws Exception {
        JSONObject result = new JSONObject();
        if(null==sysUser){
            result.put("code","1001");
            result.put("codeDesc","管理员登录超时！");
            return result;
        }
        if(null==physiqueCheck){
            result.put("code","1002");
            result.put("codeDesc","要添加的信息为空！");
            return result;
        }
        try {
            physiqueCheck.setCreateTime(Constance.currentDateTime());
            physiqueCheck.setTellerNo(sysUser.getUserNo()+"");
            //查询原体格检查信息是否存在
            YlPhysiqueCheck oldCheck = queryUserPhysiqueCheckByUserNo(physiqueCheck.getUserNo());
            if(null==oldCheck){
                checkMapper.insert(physiqueCheck);
            }else {
                QueryWrapper<YlPhysiqueCheck> physiqueCheckQueryWrapper = new QueryWrapper<>();
                physiqueCheckQueryWrapper.eq("USER_NO",physiqueCheck.getUserNo());
                checkMapper.update(physiqueCheck,physiqueCheckQueryWrapper);
            }
            //查询老人信息(健康档案状态更改为已建档)
            QueryWrapper<YlElderlyInfo> elderlyInfoQueryWrapper = new QueryWrapper<>();
            elderlyInfoQueryWrapper.eq("USER_NO",physiqueCheck.getUserNo());
            YlElderlyInfo elderlyInfo=elderlyInfoMapper.selectOne(elderlyInfoQueryWrapper);
            if(null!=elderlyInfo){
                elderlyInfo.setIsArchive("1");
                elderlyInfoMapper.updateById(elderlyInfo);
            }
            result.put("code","0000");
            result.put("codeDesc","保存成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("code","9999");
            result.put("codeDesc","保存失败！");
            return result;
        }
    }

    @Override
    public JSONObject pagedQueryUserBloodSugarInfo(int pageNum, int pageSize
            , String startDate, String endDate, String userNo) throws Exception {
        JSONObject resultData = new JSONObject();
        JSONArray dataArray = new JSONArray();
        int dataSize = 0;
        double maxValue = 10;
        try {
            QueryWrapper<YlBloodGlucose> glucoseQueryWrapper = new QueryWrapper<>();
            glucoseQueryWrapper.eq("USER_NO",userNo);
            glucoseQueryWrapper.eq("STATUS","1");
            if(StringUtils.isNotBlank(startDate)){
                startDate = Constance.disponseDate(startDate);
                glucoseQueryWrapper.ge("CREATE_DATE",startDate);
            }
            if(StringUtils.isNotBlank(endDate)){
                endDate = Constance.disponseDate(endDate);
                glucoseQueryWrapper.le("CREATE_DATE",endDate);
            }
            glucoseQueryWrapper.orderByDesc("CREATE_DATE");
            glucoseQueryWrapper.orderByDesc("CREATE_TIME");
            IPage<YlBloodGlucose> glucoseIPage = new Page<>();
            glucoseIPage.setCurrent(pageNum);
            glucoseIPage.setSize(pageSize);
            List<YlBloodGlucose> glucoseList = glucoseMapper
                    .selectPage(glucoseIPage,glucoseQueryWrapper).getRecords();
            if(null!=glucoseList&&glucoseList.size()>0){
                dataSize = glucoseList.size();
                int order = (pageNum-1)*pageNum+1;
                for(int i=0;i<glucoseList.size();i++){
                    YlBloodGlucose g = glucoseList.get(i);
                    if(null!=g){
                        JSONObject data = new JSONObject();
                        data.put("order",order+i);
                        data.put("id",g.getId());
                        data.put("glucose",Constance.Null2EmptyTrimDouble(g.getGlucoseValue()));
                        data.put("glucoseState",g.getGlucoseState());
                        data.put("date",Constance.simpleDateFormatOne(g.getCreateDate()));
                        data.put("time",Constance.simpleTimeFormatOne(g.getCreateTime()));
                        data.put("name",g.getTellerName());
                        data.put("dateTime",Constance.simpleDateFormatOne(g.getCreateDate())+" "
                                +Constance.simpleTimeFormatOne(g.getCreateTime()));
                        dataArray.add(data);
                    }
                }
                //获取最大值
                Optional<YlBloodGlucose> maxMap = glucoseList
                        .stream().max(Comparator.comparingDouble(YlBloodGlucose::getGlucoseValue));
                YlBloodGlucose maxBloodGlucose = maxMap.get();
                if(null!=maxBloodGlucose) {
                    maxValue =  Constance.Null2EmptyTrimDouble(maxBloodGlucose.getGlucoseValue())+1;
                }
            }
            //查询总条数
            int totalRecords = glucoseMapper.selectCount(glucoseQueryWrapper);
            resultData.put("code", "0000");
            resultData.put("codeDesc", "查询成功！");
            resultData.put("max",maxValue);
            resultData.put("data", dataArray);
            resultData.put("dataSize", dataSize);
            resultData.put("totalRecord", totalRecords);
            return resultData;
        } catch (Exception e) {
            e.printStackTrace();
            resultData.put("code", "9999");
            resultData.put("codeDesc", "查询失败！");
            resultData.put("data", null);
            resultData.put("dataSize", 0);
            resultData.put("totalRecord", 0);
            return resultData;
        }
    }

    @Override
    public JSONObject saveBloodSugarInfo(String userNo, String bloodSugar,SysUser sysUser) throws Exception {
        JSONObject resultData = new JSONObject();
        if(null==sysUser){
            resultData.put("code", "1001");
            resultData.put("codeDesc", "管理员登录超时！");
            return resultData;
        }
        if(StringUtils.isBlank(userNo)){
            resultData.put("code", "1002");
            resultData.put("codeDesc", "老人编号为空！");
            return resultData;
        }
        if(StringUtils.isBlank(bloodSugar)){
            resultData.put("code", "1003");
            resultData.put("codeDesc", "血糖值为空！");
            return resultData;
        }
        try {
            YlBloodGlucose glucose = new YlBloodGlucose();
            glucose.setTellerName(sysUser.getUserName());
            glucose.setCreateDate(Constance.simpleDateOne());
            glucose.setCreateTime(Constance.simpleTime());
            glucose.setStatus("1"); //正常
            glucose.setTellerNo(sysUser.getUserNo()+"");
            glucose.setUserNo(userNo);
            glucose.setGlucoseValue(Constance.Null2EmptyTrimDouble(bloodSugar));
            String glucoseState = "";
            double userGlucose = Constance.Null2EmptyTrimDouble(bloodSugar);
            if(userGlucose>bloodGlucoseHigh){
                glucoseState="2";
            }else if(userGlucose<bloodGlucoseLow){
                glucoseState="3";
            }else {
                glucoseState="1";
            }
            glucose.setGlucoseState(glucoseState);
            glucoseMapper.insert(glucose);
            resultData.put("code", "0000");
            resultData.put("codeDesc", "添加成功！");
            return resultData;
        } catch (Exception e) {
            e.printStackTrace();
            resultData.put("code", "9999");
            resultData.put("codeDesc", "添加失败！");
            return resultData;
        }
    }

    @Override
    public JSONObject deleteBloodSugarInfo(String dataInfo) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(dataInfo)){
            result.put("code", "1001");
            result.put("codeDesc", "请选择要删除的记录！");
            return result;
        }
        try {
            JSONArray dataArray = JSONArray.fromObject(dataInfo);
            for(Object obj:dataArray){
                if(null!=obj){
                    JSONObject dataObj = JSONObject.fromObject(obj);
                    if(dataObj.containsKey("id")){
                        String recordId = dataObj.getString("id");
                        //查询血糖记录信息
                        YlBloodGlucose glucose = glucoseMapper.selectById(recordId);
                        if(null!=glucose){
                            glucose.setStatus("9");
                            glucoseMapper.updateById(glucose);
                        }
                    }
                }
            }
            result.put("code", "0000");
            result.put("codeDesc", "删除成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "9999");
            result.put("codeDesc", "删除失败！");
            return result;
        }
    }

    @Override
    public JSONObject pagedQueryUserBloodPressureInfo(int pageNum, int pageSize
            , String startDate, String endDate, String userNo) throws Exception {
        JSONObject resultData = new JSONObject();
        JSONArray dataArray = new JSONArray();
        int dataSize = 0;
        try {
            QueryWrapper<YlBloodPressure> pressureQueryWrapper = new QueryWrapper<>();
            pressureQueryWrapper.eq("USER_NO",userNo);
            pressureQueryWrapper.eq("STATUS","1");
            if(StringUtils.isNotBlank(startDate)){
                startDate = Constance.disponseDate(startDate);
                pressureQueryWrapper.ge("CREATE_DATE",startDate);
            }
            if(StringUtils.isNotBlank(endDate)){
                endDate = Constance.disponseDate(endDate);
                pressureQueryWrapper.le("CREATE_DATE",endDate);
            }
            pressureQueryWrapper.orderByDesc("CREATE_DATE");
            pressureQueryWrapper.orderByDesc("CREATE_TIME");
            IPage<YlBloodPressure> pressureIPage = new Page<>();
            pressureIPage.setCurrent(pageNum);
            pressureIPage.setSize(pageSize);
            List<YlBloodPressure> pressureList = pressureMapper
                    .selectPage(pressureIPage,pressureQueryWrapper).getRecords();
            if(null!=pressureList&&pressureList.size()>0){
                dataSize = pressureList.size();
                int order = (pageNum-1)*pageNum+1;
                for(int i=0;i<pressureList.size();i++){
                    YlBloodPressure p = pressureList.get(i);
                    if(null!=p){
                        JSONObject data = new JSONObject();
                        data.put("order",order+i);
                        data.put("id",p.getId());
                        data.put("diastolic",p.getDiastolicPressure());
                        data.put("systolic",p.getSystolicPressure());
                        data.put("pressure",p.getDiastolicPressure()+"-"+p.getSystolicPressure());
                        data.put("pressureState",p.getBloodState());
                        String date = Constance.simpleDateFormatOne(p.getCreateDate());
                        data.put("date",date);
                        String time =Constance.simpleTimeFormatOne(p.getCreateTime());
                        data.put("time",time);
                        data.put("name",p.getTellerName());
                        data.put("dateTime",date+" "+time);
                        dataArray.add(data);
                    }
                }
            }
            //查询总条数
            int totalRecords = pressureMapper.selectCount(pressureQueryWrapper);
            resultData.put("code", "0000");
            resultData.put("codeDesc", "查询成功！");
            resultData.put("data", dataArray);
            resultData.put("dataSize", dataSize);
            resultData.put("totalRecord", totalRecords);
            return resultData;
        } catch (Exception e) {
            e.printStackTrace();
            resultData.put("code", "9999");
            resultData.put("codeDesc", "查询失败！");
            resultData.put("data", null);
            resultData.put("dataSize", 0);
            resultData.put("totalRecord", 0);
            return resultData;
        }
    }

    @Override
    public JSONObject saveBloodPressureInfo(String userNo, String systolicPressure
            , String diastolicPressure, SysUser sysUser) throws Exception {
        JSONObject resultData = new JSONObject();
        if(null==sysUser){
            resultData.put("code", "1001");
            resultData.put("codeDesc", "管理员登录超时！");
            return resultData;
        }
        if(StringUtils.isBlank(userNo)){
            resultData.put("code", "1002");
            resultData.put("codeDesc", "老人编号为空！");
            return resultData;
        }
        if(StringUtils.isBlank(systolicPressure)){
            resultData.put("code", "1003");
            resultData.put("codeDesc", "收缩压为空！");
            return resultData;
        }
        if(StringUtils.isBlank(diastolicPressure)){
            resultData.put("code", "1004");
            resultData.put("codeDesc", "舒张压为空！");
            return resultData;
        }
        try {
            YlBloodPressure bloodPressure = new YlBloodPressure();
            bloodPressure.setUserNo(userNo);
            bloodPressure.setTellerNo(sysUser.getUserNo()+"");
            bloodPressure.setTellerName(sysUser.getUserName());
            int diastolic = Constance.Null2EmptyTrimInt(diastolicPressure);
            bloodPressure.setDiastolicPressure(diastolic);
            int systolic = Constance.Null2EmptyTrimInt(systolicPressure);
            bloodPressure.setSystolicPressure(systolic);
            bloodPressure.setStatus("1");
            bloodPressure.setCreateDate(Constance.simpleDateOne());
            bloodPressure.setCreateTime(Constance.simpleTime());
            if(systolic>=140||diastolic>=90){
                //高血压
                bloodPressure.setBloodState("2");
            }else if(systolic<=90||diastolic<=60){
                //低血压
                bloodPressure.setBloodState("3");
            }else {
                //正常
                bloodPressure.setBloodState("1");
            }
            pressureMapper.insert(bloodPressure);
            resultData.put("code", "0000");
            resultData.put("codeDesc", "添加成功！");
            return resultData;
        } catch (Exception e) {
            e.printStackTrace();
            resultData.put("code", "9999");
            resultData.put("codeDesc", "添加失败！");
            return resultData;
        }
    }

    @Override
    public JSONObject deleteBloodPressure(String dataInfo) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(dataInfo)){
            result.put("code", "1001");
            result.put("codeDesc", "请选择要删除的记录！");
            return result;
        }
        try {
            JSONArray dataArray = JSONArray.fromObject(dataInfo);
            for(Object obj:dataArray){
                if(null!=obj){
                    JSONObject dataObj = JSONObject.fromObject(obj);
                    if(dataObj.containsKey("id")){
                        String recordId = dataObj.getString("id");
                        //查询血压记录信息
                        YlBloodPressure pressure = pressureMapper.selectById(recordId);
                        if(null!=pressure){
                            pressure.setStatus("9");
                            pressureMapper.updateById(pressure);
                        }
                    }
                }
            }
            result.put("code", "0000");
            result.put("codeDesc", "删除成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "9999");
            result.put("codeDesc", "删除失败！");
            return result;
        }
    }

    @Override
    public JSONObject pagedQueryUserNursingInfo(int pageNum, int pageSize
            , String userNo) throws Exception {
        JSONObject resultData = new JSONObject();
        JSONArray dataArray = new JSONArray();
        int dataSize = 0;
        try {
            QueryWrapper<YlHealthNursing> nursingQueryWrapper = new QueryWrapper<>();
            nursingQueryWrapper.eq("USER_NO",userNo);
            nursingQueryWrapper.eq("STATUS","1");
            nursingQueryWrapper.orderByDesc("CREATE_DATE");
            nursingQueryWrapper.orderByDesc("CREATE_TIME");
            IPage<YlHealthNursing> nursingIPage = new Page<>();
            nursingIPage.setCurrent(pageNum);
            nursingIPage.setSize(pageSize);
            List<YlHealthNursing> nursingList = nursingMapper
                    .selectPage(nursingIPage,nursingQueryWrapper).getRecords();
            if(null!=nursingList&&nursingList.size()>0){
                dataSize = nursingList.size();
                int order = (pageNum-1)*pageNum+1;
                for(int i=0;i<nursingList.size();i++){
                    YlHealthNursing n= nursingList.get(i);
                    if(null!=n){
                        JSONObject data = new JSONObject();
                        data.put("order",order+i);
                        data.put("id",n.getId());
                        data.put("nursingName",Constance.Null2EmptyTrim(n.getDegreeName()));
                        data.put("nursingDate",Constance.simpleDateFormatOne(n.getNursingDate()));
                        data.put("name",n.getTellerName());
                        data.put("dateTime",Constance.simpleDateFormatOne(n.getCreateDate())+" "
                                +Constance.simpleTimeFormatOne(n.getCreateTime()));
                        dataArray.add(data);
                    }
                }
            }
            //查询总条数
            int totalRecords = nursingMapper.selectCount(nursingQueryWrapper);
            resultData.put("code", "0000");
            resultData.put("codeDesc", "查询成功！");
            resultData.put("data", dataArray);
            resultData.put("dataSize", dataSize);
            resultData.put("totalRecord", totalRecords);
            return resultData;
        } catch (Exception e) {
            e.printStackTrace();
            resultData.put("code", "9999");
            resultData.put("codeDesc", "查询失败！");
            resultData.put("data", null);
            resultData.put("dataSize", 0);
            resultData.put("totalRecord", 0);
            return resultData;
        }
    }

    @Override
    public JSONObject saveNursingInfo(String userNo, String nursingDegree
            , String nursingDate, SysUser sysUser) throws Exception {
        JSONObject resultData = new JSONObject();
        if(null==sysUser){
            resultData.put("code", "1001");
            resultData.put("codeDesc", "管理员登录超时！");
            return resultData;
        }
        if(StringUtils.isBlank(userNo)){
            resultData.put("code", "1002");
            resultData.put("codeDesc", "老人编号为空！");
            return resultData;
        }
        if(StringUtils.isBlank(nursingDegree)){
            resultData.put("code", "1003");
            resultData.put("codeDesc", "护理等级为空！");
            return resultData;
        }
        if(StringUtils.isBlank(nursingDate)){
            resultData.put("code", "1004");
            resultData.put("codeDesc", "评估日期为空！");
            return resultData;
        }
        try {
            //查询老人信息
            QueryWrapper<YlElderlyInfo> elderlyInfoQueryWrapper = new QueryWrapper<>();
            elderlyInfoQueryWrapper.eq("USER_NO",userNo);
            YlElderlyInfo  elderlyInfo = elderlyInfoMapper.selectOne(elderlyInfoQueryWrapper);
            if(null==elderlyInfo){
                resultData.put("code", "1005");
                resultData.put("codeDesc", "老人信息不存在！");
                return resultData;
            }
            //查询护理评估等级信息
            QueryWrapper<YlCost> costQueryWrapper = new QueryWrapper<>();
            costQueryWrapper.eq("COST_NO",nursingDegree);
            YlCost cost = costMapper.selectOne(costQueryWrapper);
            if(null==cost){
                resultData.put("code", "1006");
                resultData.put("codeDesc", "护理等级不存在！");
                return resultData;
            }
            YlHealthNursing nursing = new YlHealthNursing();
            nursing.setUserNo(userNo);
            nursing.setTellerNo(sysUser.getUserNo()+"");
            nursing.setTellerName(sysUser.getUserName());
            nursing.setStatus("1");
            nursing.setCreateDate(Constance.simpleDateOne());
            nursing.setCreateTime(Constance.simpleTime());
            nursing.setNursingDegree(nursingDegree);
            nursing.setDegreeName(cost.getCostName());
            nursing.setNursingDate(Constance.disponseDate(nursingDate));
            nursing.setReadStatus("0"); //阅读状态为待阅读
            nursingMapper.insert(nursing);
            elderlyInfo.setIsNotice("1");
            elderlyInfoMapper.updateById(elderlyInfo);
            resultData.put("code", "0000");
            resultData.put("codeDesc", "添加成功！");
            return resultData;
        } catch (Exception e) {
            e.printStackTrace();
            resultData.put("code", "9999");
            resultData.put("codeDesc", "添加失败！");
            return resultData;
        }
    }

    @Override
    public JSONObject deleteNursingInfo(String dataInfo) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(dataInfo)){
            result.put("code", "1001");
            result.put("codeDesc", "请选择要删除的记录！");
            return result;
        }
        try {
            JSONArray dataArray = JSONArray.fromObject(dataInfo);
            for(Object obj:dataArray){
                if(null!=obj){
                    JSONObject dataObj = JSONObject.fromObject(obj);
                    if(dataObj.containsKey("id")){
                        String recordId = dataObj.getString("id");
                        //查询护理等级信息
                        YlHealthNursing nursing = nursingMapper.selectById(recordId);
                        if(null!=nursing){
                            nursing.setStatus("9");
                            nursingMapper.updateById(nursing);
                        }
                    }
                }
            }
            result.put("code", "0000");
            result.put("codeDesc", "删除成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "9999");
            result.put("codeDesc", "删除失败！");
            return result;
        }
    }

    @Override
    public JSONObject readNursingInfo(String pensionNo) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code", "1001");
            result.put("codeDesc", "养老院编号为空！");
            return result;
        }
        try {
            nursingMapper.readHealthyNursingInfo(pensionNo);
            result.put("code", "0000");
            result.put("codeDesc", "阅读成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "9999");
            result.put("codeDesc", "阅读失败！");
            return result;
        }
    }
}
